package com.coding.controller;

import com.coding.dto.RestBean;
import com.coding.service.LikeService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/7/8 16:01:36
 */
@RestController
@RequestMapping("/like")
@Slf4j
/**
 * 控制器类，处理喜欢/点赞相关的操作。
 * 包括增加点赞数和定期将点赞数同步到数据库。
 */
public class LikeController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private LikeService service;

    /**
     * 增加点赞数。
     *
     * @param liveStreamId 直播间ID
     * @return 返回响应实体，表示点赞操作是否成功。
     */
    @PostMapping("/add-like")
    public RestBean<String> like(@RequestParam String liveStreamId) {
        return service.like(liveStreamId);
    }

    // 获取点赞数
    @GetMapping("/liveStream/{liveStreamId}")
    public ResponseEntity<Map<String, Object>> getLikes(@PathVariable Long liveStreamId) {
        String key = "like_count:" + liveStreamId;
        String likeCount = redisTemplate.opsForValue().get(key);
        Map<String, Object> response = new HashMap<>();
        response.put("likeCount", likeCount == null ? 0 : Integer.parseInt(likeCount));
        return ResponseEntity.ok(response);
    }
}


